#include"../include/lib_headers.h"

char* list_file(char *source_file_with_path, char *destination_file_path) {
	node *temp;
	char str[(BLOCKSIZE) + 1]="";
	
	/* VFS not mounted */
	if (h == NULL || l1 == NULL) {
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_04);	
		return output_message;
	}

	/* Insufficient Arguments */	
	if(strlen(source_file_with_path) == 0 || strlen(destination_file_path) == 0){
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_00);	
		return output_message;
	}

	/* Source file path Not found */
	//if (find_node(l1->next, source_file_with_path) == NULL) {
	if(search(bstRoot,source_file_with_path)==NULL || source_file_with_path[0] != '/' ){	
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_01);	
		return output_message;
	} else
		temp = find_node(l1->next, source_file_with_path);
		
	/* A directory cannot be listed */	
	if(strcmp(find_node(l1->next, source_file_with_path)->fd_pointer->fileType, "dir") == 0){
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_02);	
		return output_message;
	}	

	/* Not a Text File */		
	if(strcmp(temp->fd_pointer->fileType, "txt") !=0){
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_02);	
		return output_message;
	}	

	/* Cannot create an OutputFile */
	FILE *f = fopen(destination_file_path, "w");
	if (f == NULL) {
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_03);	
		return output_message;
	}

	/* Cannot Open the VFS */
	FILE *fp = fopen(h->VFS_Label, "rb");
	if (fp == NULL) {
		sprintf(output_message,"%s %s","listfile_FAILURE",ERR_VFS_LISTFILE_01);	
		return output_message;
	}


	fseek(fp,
			sizeof(hd) + sizeof(fd) * h->maxFds
					+ sizeof(int) * h->maxFds
					+ (BLOCKSIZE) * (temp->fd_pointer->blockno), SEEK_SET);
	fread(str, temp->fd_pointer->fileSize, 1, fp);
	fwrite(str, strlen(str), 1, f);
	fclose(fp);
	fclose(f);
	sprintf(output_message,"%s","listfile_SUCCESS");	
	return output_message;
}

